package DAO;

import java.util.Vector;

import DTO.DatabaseDTO;
import DTO.TableDTO;



public class TableDAO {
	private String _DatabasePath;

	public TableDAO(String databasePath) {
		_DatabasePath = databasePath;
	}

	public void addTable(TableDTO tableDTO) throws Exception {
		if(!testTableCol(tableDTO))
		{
			throw new Exception("Table must have unique column name!");
		}
		if(!testTableName(tableDTO.get_name()))
		{
			throw new Exception("Table name must be unique!");
		}
		DatabaseDAO dbDAO = new DatabaseDAO(_DatabasePath);
		DatabaseDTO dbDTO = dbDAO.getDatabase();
		Vector<TableDTO> tableList = new Vector<TableDTO>();
		if (dbDTO != null)
			tableList = dbDTO.get_tableList();
		tableList.add(tableDTO);
		dbDTO = new DatabaseDTO(null);
		dbDTO.set_tableList(tableList);
		dbDAO.save(dbDTO);
	}
	
	private boolean testTableCol(TableDTO tableDTO)
	{
		for(int i=0; i<tableDTO.get_colInfoList().size()-1; i++)
		{
			for(int j=i+1;j<tableDTO.get_colInfoList().size(); j++ )
			{
				if(tableDTO.get_colInfoList().elementAt(i).get_colName().equals(tableDTO.get_colInfoList().elementAt(j).get_colName()))
				{
					return false;
				}
			}
		}
		return true;
	}
	
	private boolean testTableName(String tableName) throws Exception
	{
		Vector<TableDTO> tableList = getAllTable();
		for(int i=0; i<tableList.size(); i++)
		{
			if(tableList.elementAt(i).get_name().equals(tableName))
				return false;
		}
		return true;
	}

	public Vector<TableDTO> getAllTable() throws Exception {
		DatabaseDAO dbDAO = new DatabaseDAO(_DatabasePath);
		DatabaseDTO dbDTO = dbDAO.getDatabase();
		if (dbDTO == null)
			return new Vector<TableDTO>();
		return dbDTO.get_tableList();
	}

	public TableDTO getTable(String tableName) throws Exception {
		Vector<TableDTO> tableList = getAllTable();
		for (int i = 0; i < tableList.size(); i++) {
			String temp = tableList.elementAt(i).get_name().toUpperCase();
			if(tableName.toUpperCase().equals(temp)) {
				return tableList.elementAt(i);
			}
		}
		throw new Exception("table not found!");
	}

	public void removeTable(String tableName) throws Exception {
		DatabaseDAO dbDAO = new DatabaseDAO(_DatabasePath);
		DatabaseDTO dbDTO = dbDAO.getDatabase();
		Vector<TableDTO> tableList = dbDTO.get_tableList();
		for (int i = 0; i < tableList.size(); i++)
			if (tableList.elementAt(i).get_name()
					.compareToIgnoreCase(tableName) == 0)
				tableList.remove(i);
		dbDTO.set_tableList(tableList);
		dbDAO.save(dbDTO);
	}
}
